package channel.master;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;

/**
 *
 * @author Michael Hanns
 *
 */
public class MasterChannelTest {

    private static String masterChannelNotFound = "Can't get master channel ip!";

    public static void main(String[] args) {
        String channelIP = "127.0.0.1";
        if (!channelIP.equals(masterChannelNotFound)) {
            try {
                InetAddress ip = InetAddress.getByName(channelIP);

                Socket echoSocket = new Socket(ip, 725);
                PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
                BufferedReader in =
                        new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

                // Send command to recieve server data..
                out.println("GETCHANNELS");
                // Get the number of servers from the first line of the reply
                String line = in.readLine();

                if (line != null) {
                    int numServers = Integer.parseInt(line);

                    for (int x = 0; x < numServers; x++) {
                        System.out.println(in.readLine());
                    }
                } else {
                    System.out.println("No response from server.");
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getDefaultChannelIP() {
        try {
            URL whatismyip = new URL("http://servertools.whatisthynameadventurer.com/officialIP.txt");
            InputStream stream = whatismyip.openStream();

            BufferedReader in = new BufferedReader(new InputStreamReader(stream));

            String ip = in.readLine();

            stream.close();
            in.close();

            if (ip != null) {
                return ip;
            }

            return masterChannelNotFound;
        } catch (IOException e) {
            e.printStackTrace();
            return masterChannelNotFound;
        }
    }
}
